<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\Order;
use app\admin\model\VipOrder;
use app\common\controller\Api;
use think\Request;
use Yansongda\Pay\Exceptions\Exception;

class Vip extends Api
{

    protected $noNeedLogin = ['getVip','getVipInfo'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->model = new \app\admin\model\Vip();
    }

    public function getVip()
    {
        $list = $this->model->select();
        $banner = $vipbanner = config('site.vipbanner');
        foreach ($vipbanner as $key => $val){
            $banner[$key] = cdnurl($val,true);
        }
        foreach ($list as $key=> $value){
            $value['pramsjson'] = is_array($value['pramsjson']) ? $value['pramsjson'] : json_decode($value['pramsjson'], true);
        }
        $user = $this->auth->getUser();

        $data = [
            'list'=>$list,
            'banner'=>$banner,
        ];
        $this->success('返回成功',$data);
    }
    public function getVipInfo(){
        $id = $this->request->param('id');
        $is_pay = false;
        $endTimeText='';
        $user = $this->auth->getUser();
        if($user){
            $is_pay = $user['vip_end_time'] > 0 && $user['vip_end_time'] > time() ? true : false;
            $endTimeText = date('Y年m月d日',$user['vip_end_time']);
        }
        $info = $this->model->find($id);
        $info['pramsjson'] = is_array($info['pramsjson']) ? $info['pramsjson'] : json_decode($info['pramsjson'], true);
        $this->success('',[
            'info'=>$info,
            'is_pay'=>$is_pay,
            'endTimeText'=>$endTimeText,
        ]);
    }
    public function createOrder(){

        $this->error("请联系管理员在后台开通");
            $out_trade_no = $this->ordersnum();
            $title = '会员购买';
            $amount = $this->request->request('amount');
            $type = $this->request->request('type', $this->request->request('paytype'));
            $method = $this->request->request('method', 'wap');
            $openid = $this->request->request('openid', '');
            $vipId= $this->request->request('vip_id');
            $auth_code = $this->request->request('auth_code', '');
            $notifyurl = !empty($params['notifyurl']) ? $params['notifyurl'] : $this->request->root(true) . '/api/vip/notifyx/paytype/' . $type;
            $returnurl = !empty($params['returnurl']) ? $params['returnurl'] : $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

            if (!$amount || $amount < 0) {
                $this->error("支付金额必须大于0");
            }

            if (!$type || !in_array($type, ['alipay', 'wechat'])) {
                $this->error("支付类型错误");
            }
            $model = new VipOrder();
            $model->startTrans();
            try {
                $orderdata = [
                    'order_sn' => $out_trade_no,
                    'price' => $amount,
                    'pay_type' => $type,
                    'user_id' => $this->auth->id,
                    'vip_id'=>$vipId,
                    'create_time' => time(),
                ];
                $model->save($orderdata);
                $params = [
                    'type'         => $type,
                    'orderid'=>$out_trade_no,
                    'out_trade_no' => $out_trade_no,
                    'title'        => $title,
                    'amount'       => $amount,
                    'method'       => $method,
                    'openid'       => $openid,
                    'auth_code'    => $auth_code,
                    'notifyurl'    => $notifyurl,
                    'returnurl'    => $returnurl,
                ];

                $res = \addons\epay\library\Service::submitOrder($params);
                if($type=='alipay'){
                    $pay['content'] = $res->getContent();
                }else{
                    $pay = $res;
                }
                $this->model->commit();

                $pay['order_sn'] = $out_trade_no;
                $this->success("创建成功",$pay);
            }catch (Exception $e){
                $this->model->rollback();
                $this->error($e->getMessage());
            }

    }


    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        $post = $this->request->param();
        $ordermodel = new VipOrder();

        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $order =  $ordermodel->where(['order_sn'=>$post['out_trade_no']])->find();
            $transaction_id = $data['transaction_id'] ??$data['trade_no'];
            $ordermodel->where(['order_sn'=>$out_trade_no])->update(['pay_status'=>2,'pay_time'=>time(),'transaction_id'=>$transaction_id]);
            $user = \app\admin\model\User::get($order['user_id']);
            $vip = $this->model->where(['id'=>$order['vip_id']])->find();
            $time = time() + $vip['mouth']*24*3600*30;
            $user->save(['vip_time'=>$time]);
            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }


    public function getOrderList(){
        $vipOrderModel = new VipOrder();
        $list = $vipOrderModel->with(['user','vip'])->where(['user_id'=>$this->auth->id])->select();
        $this->success('返回成功',$list);
    }
    /*
* 生成订单号
* */
    protected function ordersnum()
    {
        $code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T');
        $char = $code[intval(date('Y')) - 2019] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        $res = $this->model->where("order_sn='$char'")->find();
        if ($res) {
            $this->ordersnum();
        }
        return $char;
    }
    public function delOrder(){
        $this->model->whereBetween('create_time',[time()-15*60,time()])->where(['pay_status'=>1])->delete();
        $this->success("删除成功");
    }
}